package com.study.apect;

import com.study.config.DataSourceEnums;
import com.study.config.DynamicRoutingDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author : zhuyanpeng.zhuyanpeng
 * @Description: :
 * @date :Create in  2019/9/10- 14:38
 * @Version: V1.0
 * @Modified By:
 **/
@Aspect
@Component
@Slf4j
public class DataSourceAspect  {
    @Pointcut("@annotation(com.study.apect.DataSourceSign)")
    public void dataFilter(){
    }

    @Around("dataFilter()")
    @Order(1)
    public Object beforDataFilter(ProceedingJoinPoint point) throws Throwable {
        System.out.println("进入 [Before] 时的时间"+ DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        MethodSignature signature =(MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSourceSign dataSourceSign = method.getAnnotation(DataSourceSign.class);
        if (dataSourceSign == null) {
            //方法上面没有包含此注解判断类上面是否有此注解
            dataSourceSign = AnnotationUtils.findAnnotation(point.getTarget().getClass(), DataSourceSign.class);
        }
        if (dataSourceSign == null){
            //连接默认的数据库
            DynamicRoutingDataSource.setDataSource(DataSourceEnums.FIRST);
        }else{
            DynamicRoutingDataSource.setDataSource(dataSourceSign.value());

        }
        try {
            log.warn("current db is>>>>>"+DynamicRoutingDataSource.getDataSource());
            return point.proceed();
        } finally {
            DynamicRoutingDataSource.clearDataSource();
        }
    }
}
